#include "pSocket.h"

pSocket::pSocket()
{
	_recvBuffer = new byte[BUFFER_SIZE];
	_baseSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if(_baseSocket == INVALID_SOCKET)
	{
		closesocket(_baseSocket);
		throw INVALID_SOCKET;
	}
}

void pSocket::InitWinSock(WSADATA& wsaData)
{
	if(WSAStartup(MAKEWORD(2,2), &wsaData) != 0)
	{
		throw SOCKET_ERROR;
	}
}

/*
realese socekts resources (allocated when WSAStartup command called) 
can return the follwing execptions:
    1. WSANOTINITIALISED - when the WSAStartup doesnt called or didnt succeed.
	2. WSAENETDOWN - network substytem failed.
	3. WSAEINPROGRESS - bloacking windwos sockets function is in progress.
*/
void pSocket::CleanWinSock()
{
	int err = WSACleanup();
	if (err != 0)
	{
		throw err;
	}
}

pSocket::pSocket(SOCKET sd)
{
	_recvBuffer = new byte[BUFFER_SIZE];
	_baseSocket = sd;
}

void pSocket::Send(const byte* buffer, int len) const
{
	int sent = 0;
	do
	{
	sent += send(_baseSocket, reinterpret_cast<const char *>(buffer), len, 0);
	if(sent == SOCKET_ERROR)
		throw sent;
	}
	while(sent < len);
}

int pSocket::Receive(byte * buffer, SOCKET socket, int nBytes)
{
	int recvd = 0;
	int totalcnt = 0;
	memset(buffer, 0, BUFFER_SIZE);
	recvd = recv(((socket == NULL) ? _baseSocket : socket), reinterpret_cast<char *>(_recvBuffer), nBytes, 0);
	if(recvd == SOCKET_ERROR)
		throw WSAGetLastError();
	return recvd;
}

pSocket::~pSocket()
{
	delete[] _recvBuffer;
	if(closesocket(_baseSocket) == SOCKET_ERROR)
		throw SOCKET_ERROR;

}

